"""
团队管理API
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.team import Team
from app.models.user import User
from app.utils.decorators import admin_required
from app.utils.validators import validate_team_data
from marshmallow import ValidationError

teams_bp = Blueprint('teams', __name__)

@teams_bp.route('/', methods=['GET'])
@jwt_required()
def get_teams():
    """获取团队列表"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.find_by_id(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户所属的团队
        teams = Team.get_user_teams(current_user_id)
        
        return jsonify({
            'teams': [team.to_dict() for team in teams]
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取团队列表失败: {str(e)}'}), 500

@teams_bp.route('/', methods=['POST'])
@jwt_required()
def create_team():
    """创建团队"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.find_by_id(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_team_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 创建团队
        team = Team(
            name=validated_data['name'],
            description=validated_data.get('description', ''),
            owner_id=current_user_id
        )
        
        db.session.add(team)
        db.session.commit()
        
        # 添加创建者为团队成员
        team.add_member(current_user_id, 'owner')
        
        return jsonify({
            'message': '团队创建成功',
            'team': team.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建团队失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>', methods=['GET'])
@jwt_required()
def get_team(team_id):
    """获取团队详情"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限访问团队
        if not team.is_member(current_user_id):
            return jsonify({'error': '无权限访问此团队'}), 403
        
        return jsonify({
            'team': team.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取团队详情失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>', methods=['PUT'])
@jwt_required()
def update_team(team_id):
    """更新团队信息"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限修改团队
        if team.owner_id != current_user_id:
            return jsonify({'error': '无权限修改此团队'}), 403
        
        data = request.get_json()
        
        # 验证数据
        try:
            validated_data = validate_team_data(data)
        except ValidationError as e:
            return jsonify({'error': '数据验证失败', 'details': e.messages}), 400
        
        # 更新团队信息
        team.name = validated_data['name']
        team.description = validated_data.get('description', '')
        
        db.session.commit()
        
        return jsonify({
            'message': '团队更新成功',
            'team': team.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新团队失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>', methods=['DELETE'])
@jwt_required()
def delete_team(team_id):
    """删除团队"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限删除团队
        if team.owner_id != current_user_id:
            return jsonify({'error': '无权限删除此团队'}), 403
        
        db.session.delete(team)
        db.session.commit()
        
        return jsonify({
            'message': '团队删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除团队失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>/members', methods=['GET'])
@jwt_required()
def get_team_members(team_id):
    """获取团队成员列表"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限访问团队
        if not team.is_member(current_user_id):
            return jsonify({'error': '无权限访问此团队'}), 403
        
        members = team.get_members()
        
        return jsonify({
            'members': [member.to_dict() for member in members]
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取团队成员失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>/members', methods=['POST'])
@jwt_required()
def add_team_member(team_id):
    """添加团队成员"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限管理团队
        if team.owner_id != current_user_id:
            return jsonify({'error': '无权限管理此团队'}), 403
        
        data = request.get_json()
        user_id = data.get('user_id')
        role = data.get('role', 'member')
        
        if not user_id:
            return jsonify({'error': '用户ID不能为空'}), 400
        
        # 检查用户是否存在
        user = User.find_by_id(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 添加团队成员
        team.add_member(user_id, role)
        
        return jsonify({
            'message': '团队成员添加成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'添加团队成员失败: {str(e)}'}), 500

@teams_bp.route('/<int:team_id>/members/<int:user_id>', methods=['DELETE'])
@jwt_required()
def remove_team_member(team_id, user_id):
    """移除团队成员"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)
        
        if not team:
            return jsonify({'error': '团队不存在'}), 404
        
        # 检查用户是否有权限管理团队
        if team.owner_id != current_user_id:
            return jsonify({'error': '无权限管理此团队'}), 403
        
        # 移除团队成员
        team.remove_member(user_id)
        
        return jsonify({
            'message': '团队成员移除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'移除团队成员失败: {str(e)}'}), 500


@teams_bp.route('/<int:team_id>/leave', methods=['DELETE'])  # 改成 DELETE
@jwt_required()
def leave_team(team_id):
    """当前用户退出团队"""
    try:
        current_user_id = get_jwt_identity()
        team = Team.find_by_id(team_id)

        if not team:
            return jsonify({'error': '团队不存在'}), 404

        if not team.is_member(current_user_id):
            return jsonify({'error': '您不是该团队成员，无法退出'}), 403


        team.remove_member(current_user_id)

        return jsonify({
            'message': '已成功退出团队'
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'退出团队失败: {str(e)}'}), 500


